package main

import (
	"bufio"
	"encoding/binary"
	"fmt"
	"io/ioutil"
	"net"
	"os"
)

const (
	filename  = "fileini.ini"
	sevaraddr = "127.0.0.1:8081"
)

var foby []byte
var size int64

func main() {
	fo, err := os.Open(filename)
	if err != nil {
		fmt.Println("配置文件打开失败", err)
	}
	defer fo.Close()
	s, err := fo.Stat()
	if err != nil {
		fmt.Println(err)
	}
	size = s.Size()
	fby := bufio.NewReader(fo)
	foby = make([]byte, size)
	_, err = fby.Read(foby)
	if err != nil {
		fmt.Println(36, err.Error())
		os.Exit(1)
	}
	list, err := net.Listen("tcp", sevaraddr)
	if err != nil {
		fmt.Println(err)
	}
	defer list.Close()
	fmt.Println("同步服务启动成功，等待连接。。。")
	by := make([]byte, 128)
	for {
		conn, err := list.Accept()
		if err != nil {
			fmt.Println(err)
			continue
		}
		fmt.Println("欢迎：", conn.RemoteAddr().String())
		n, err := conn.Read(by)
		if err != nil {
			fmt.Println(err)
			continue
		}
		getsay := string(by[:n])
		fmt.Println(conn.RemoteAddr().String(), "发送来：", getsay)
		if getsay == "get" {
			go getini(conn)
			continue
		} else {
			go putfile(conn, getsay)
			continue
		}
	}
}

func getini(conn net.Conn) {
	defer conn.Close()
	_, err := conn.Write(foby)
	if err != nil {
		fmt.Println("配置文件发送失败", err)
		return
	}
}

func putfile(conn net.Conn, name string) {
	defer conn.Close()
	file_1, file_name, err := getFile(name)
	if err != nil {
		fmt.Println("查询失败")
		return
	}
	file_by := shujupacket(file_1, file_name)
	_, err = conn.Write(file_by)
	if err != nil {
		fmt.Println(name, "发送失败！")
	} else {
		fmt.Println(name, "发送成功！")
	}
}

func getFile(str string) (*os.File, string, error) {
	dir, err := ioutil.ReadDir(".")
	for _, filename := range dir {
		fmt.Println(filename.Name())
		dir_1, _ := ioutil.ReadDir("./" + filename.Name())
		for _, filename_1 := range dir_1 {
			if str == filename_1.Name() {
				ff, err := os.Open(filename.Name() + "/" + str)
				if err != nil {
					fmt.Println(str, "打开失败")
					return nil, "", err
				}
				return ff, filename.Name(), nil
			}
		}
	}
	return nil, "", err
}

func shujupacket(file *os.File, dir string) []byte {
	fmt.Println("获得目录：", dir)
	leng, _ := file.Stat()
	length := leng.Size()
	fmt.Println("文件长度：", length)
	filesj := make([]byte, length)
	bf := bufio.NewReader(file)
	n, err := bf.Read(filesj)
	if n != int(length) || err != nil {
		fmt.Println("读取文件失败shujupacket")
		return nil
	}
	bytes := make([]byte, length+10)
	bytes[0] = 0xff
	copy(bytes[2:10], inttobyte(uint64(length)))
	copy(bytes[10:], filesj)
	switch dir {
	case "小米":
		bytes[1] = 0x01
	case "华为":
		bytes[1] = 0x02
	case "三星":
		bytes[1] = 0x03
	case "windows":
		bytes[1] = 0x04
	case "mac":
		bytes[1] = 0x05
	default:
		bytes[1] = 0x06
	}
	return bytes
}

func inttobyte(i uint64) []byte {
	b := make([]byte, 8)
	binary.BigEndian.PutUint64(b, i)
	return b
}
